package pers.corvey.studyjava.controller;

import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import pers.corvey.studyjava.exception.InternalServerErrorException;
import pers.corvey.studyjava.model.Example;
import pers.corvey.studyjava.model.form.ExampleForm;
import pers.corvey.studyjava.service.ExampleService;

@Controller
@RequestMapping("/examples")
public class ExampleController {

    @Autowired
    private ExampleService exampleService;
    
    @GetMapping(value="/{exampleId}", headers="Accept=text/html")
    public String showOne() {
        return "forward://html/showExample.html";
    }
    
    @GetMapping(value="/addExample", headers="Accept=text/html")
    public String showAdd() {
        return "forward://addExample.html";
    }
    
    @GetMapping(headers="Accept=text/html")
    public String showAll() {
        return "forward://html/showExamples.html";
    }
    
    @GetMapping
    @ResponseBody
    public Iterable<Example> getExamples() {
        return exampleService.getExamples();
    }
    
    @GetMapping("/{exampleId}")
    @ResponseBody
    public Example getExampleById(@PathVariable String exampleId) {
        return exampleService.getExampleById(exampleId);
    }
    
    @PostMapping
    @ResponseBody
    public Example createExample(ExampleForm form) {
        Example example;
        try {
            example = form.toExample();
        } catch (IOException e) {
            throw new InternalServerErrorException("服务器发生异常！", e);
        }
        return exampleService.createExample(example);
    }
    
}
